package br.com.passeionaweb.android.TabelaFipe;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import br.com.passeionaweb.android.TabelaFipe.db.PricesDatabaseHelper;

import android.content.Context;
import android.net.Uri;

public class DataProvider {

	private static final String BASE_URL = "http://quatrorodas.abril.com.br/compre-seu-carro/static/javascripts/";

	private static final String MAKE_URL = BASE_URL + "price-table-makes";
	private static final String MODEL_URL = BASE_URL + "price-table-models";
	private static final String YEAR_URL = BASE_URL + "price-table-years";
	private static final String VERSION_URL = BASE_URL + "price-table-versions";
	private static final String PRICE_URL = "http://quatrorodas.abril.com.br/compre-seu-carro/tabela-de-precos";

	private static final int MAKE = 0;
	private static final int MODEL = 1;
	private static final int YEAR = 2;
	private static final int VERSION = 3;
	private static final int PRICE = 4;
	private static final String KEY_MAKE = "make";
	private static final String KEY_MODEL = "model";
	private static final String KEY_YEAR = "year";
	private static final String KEY_VERSION = "version";

	private String make;
	private String model;
	private String year;
	private String version;

	private CacheManager cache;
	private PricesDatabaseHelper pricesDatabase;

	public DataProvider(Context context) {
		cache = new CacheManager(context);
		pricesDatabase = new PricesDatabaseHelper(context);
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public String getMake() {
		return make;
	}

	public void setMake(String make) {
		this.make = make;
	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public String getPrice() throws Exception {
		InputStream responseStream = getDataStream(PRICE);

		BufferedReader reader = new BufferedReader(new InputStreamReader(responseStream));
		String line = reader.readLine();
		StringBuilder responseBuilder = new StringBuilder();
		while (line != null) {
			responseBuilder.append(line);
			line = reader.readLine();
		}
		String responseData = responseBuilder.toString();
		String partialHtml = responseData.substring(responseData.indexOf("R$"));
		String price = partialHtml.substring(0, partialHtml.indexOf('<'));
		pricesDatabase.insertPrice(make, model, year, version, price);
		return price;
	}

	public String getKey(int type) {
		switch (type) {
			case MAKE:
				return KEY_MAKE;
			case MODEL:
				return KEY_MODEL;
			case YEAR:
				return KEY_YEAR;
			case VERSION:
				return KEY_VERSION;
			default:
				return null;
		}
	}

	public String[] getMakes() throws Exception {
		try {
			if (!cache.isMakesfileOld()) {
				return jsonToArray(cache.getMakesJSON(), MAKE);
			}
		} catch (IOException e) {
			// TODO log error
		}

		String makes = getData(MAKE);
		cache.saveMakesJSON(makes);
		return jsonToArray(makes, MAKE);

	}

	public String[] getModels() throws Exception {
		try {
			if (!cache.isModelsFileOld(this.make)) {
				return jsonToArray(cache.getModelsJSON(this.make), MODEL);
			}
		} catch (IOException e) {
			// TODO log error
		}

		String models = getData(MODEL);
		cache.saveModelsJSON(make, models);
		return jsonToArray(models, MODEL);
	}

	public String[] getYears() throws Exception {
		return jsonToArray(getData(YEAR), YEAR);
	}

	public String[] getVersions() throws Exception {
		return jsonToArray(getData(VERSION), VERSION);
	}

	public String getData(int type) throws Exception {

		InputStream responseData = getDataStream(type);
		StringBuilder json = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(responseData));
		String line = reader.readLine();
		while (line != null) {
			json.append(line);
			line = reader.readLine();
		}
		return json.toString();
	}

	public String[] jsonToArray(String json, int type) throws JSONException {
		ArrayList<String> items = new ArrayList<String>();
		JSONArray JSONItems = new JSONArray(json.toString());
		for (int i = 0; i < JSONItems.length(); i++) {
			JSONObject obj = JSONItems.getJSONObject(i);
			items.add(obj.getString(getKey(type)));
		}

		return items.toArray(new String[items.size()]);

	}

	private InputStream getDataStream(int type) throws Exception {
		return new URL(buildURI(type)).openStream();
	}

	private String buildURI(int type) {
		switch (type) {
			case MAKE:
				return MAKE_URL;
			case MODEL:
				return MODEL_URL + "?" + KEY_MAKE + "=" + URLEncoder.encode(make);
			case YEAR:
				return YEAR_URL + "?" + KEY_MAKE + "=" + URLEncoder.encode(make) + "&" + KEY_MODEL
						+ "=" + URLEncoder.encode(model);
			case VERSION:
				return VERSION_URL + "?" + KEY_MAKE + "=" + URLEncoder.encode(make) + "&"
						+ KEY_MODEL + "=" + URLEncoder.encode(model) + "&" + KEY_YEAR + "="
						+ URLEncoder.encode(year);
			case PRICE:
				return PRICE_URL + "?" + KEY_MAKE + "=" + URLEncoder.encode(make) + "&" + KEY_MODEL
						+ "=" + URLEncoder.encode(model) + "&" + KEY_YEAR + "="
						+ URLEncoder.encode(year) + "&" + KEY_VERSION + "="
						+ URLEncoder.encode(version);
			default:
				break;
		}
		return null;
	}
}
